package org.psyduck.security.service;

import org.psyduck.common.base.BaseService;
import org.psyduck.common.constant.Constants;
import org.psyduck.security.dao.SecurityMenuDao;
import org.psyduck.security.dao.UserDao;
import org.psyduck.security.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SecurityUserService extends BaseService<UserDao, User> {

    @Autowired
    SecurityMenuDao securityMenuDao;

    @Cacheable(value = "userAuth" ,key = "#userId")
    public List<GrantedAuthority> getCurrentUserAuthorities(String userId){
        List<String> permissions;
        if(userId.equals(Constants.User.SUPER_ADMIN_ID)){
            permissions = securityMenuDao.getAllPermissions();
        }else{
            permissions = securityMenuDao.getCurrentUserPermissions(userId);
        }
        return permissions.stream().flatMap(it -> Arrays.stream(it.split(",")))
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

}